﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Shapes;
using PairingMatrix.Common.Enum;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class DragProjectCardBehavior : Behavior<ProjectCardControl>
    {
        private Canvas _canvas;
        private bool _isMouseCaptured;
        private Point _mouseStartPosition;
        private IProjectCardViewModel _nearestProjectCard;
        private ContentPresenter _parent;
        private ProjectCardViewModel _projectCardViewModel;


        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
                                       {
                                           _projectCardViewModel = (ProjectCardViewModel) AssociatedObject.DataContext;
                                           _projectCardViewModel.PropertyChanged += ProjectCard_PropertyChanged;

                                           if (_projectCardViewModel.Position.X == 0 &&
                                               _projectCardViewModel.Position.Y == 0)
                                           {
                                               _projectCardViewModel.Position =
                                                   ((CardWallViewModel) ControlRegistry.CardWallControl.DataContext).
                                                       GetDefaultPositionAsPerDevelopmentStage(
                                                           _projectCardViewModel.DevStage);
                                           }
                                           else
                                           {
                                               SetCardInPosition();
                                           }
                                           _projectCardViewModel.CenterPoint =
                                               new Point(
                                                   _projectCardViewModel.Position.X + AssociatedObject.ActualWidth/2,
                                                   _projectCardViewModel.Position.Y + AssociatedObject.ActualHeight/2);
                                       };


            AssociatedObject.MouseLeftButtonDown += (sender, e) =>
                                                    {
                                                        if (_parent == null)
                                                        {
                                                            _parent =
                                                                (ContentPresenter)
                                                                VisualTreeHelper.GetParent(AssociatedObject);
                                                            _canvas = (Canvas) VisualTreeHelper.GetParent(_parent);
                                                        }
                                                        _mouseStartPosition = e.GetPosition(_canvas);
                                                        AssociatedObject.CaptureMouse();
                                                        _isMouseCaptured = true;
                                                    };

            CardWallControl cardWallControl = ControlRegistry.CardWallControl;
            AssociatedObject.MouseLeftButtonUp += (sender, e) =>
                                                  {
                                                      AssociatedObject.ReleaseMouseCapture();
                                                      _isMouseCaptured = false;

                                                      double currentTop = Canvas.GetTop(_parent);
                                                      double currentLeft = Canvas.GetLeft(_parent);
                                                      var cardWallViewModel =
                                                          ((ICardWallViewModel) cardWallControl.DataContext);
                                                      if (cardWallViewModel.SelectedStoryStatus != StoryStatus.None)
                                                      {
                                                          _projectCardViewModel.DevStage = cardWallViewModel.SelectedStoryStatus;
                                                      }

                                                      cardWallViewModel.SelectedStoryStatus = StoryStatus.None;

//                                                      if (_nearestProjectCard != null)
//                                                      {
//                                                          cardWallViewModel.AttachSecondaryProjectCardToProjectCard(_projectCardViewModel, _nearestProjectCard, currentLeft, currentTop);
//                                                      }
//                                                      else
//                                                      {
                                                          _projectCardViewModel.Position = new Point(currentLeft, currentTop);
//                                                          cardWallViewModel.DetachProjectCardFromAllProjectCards(_projectCardViewModel);
//                                                      }

                                                      foreach (
                                                          IProjectCardViewModel projectCard in
                                                              cardWallViewModel.ProjectCards)
                                                      {
                                                          projectCard.ShowHighlighted = false;
                                                      }
                                                  };

            AssociatedObject.MouseMove += (sender, e) =>
                                          {
                                              if (_isMouseCaptured)
                                              {
                                                  if (_parent == null)
                                                  {
                                                      _parent =
                                                          (ContentPresenter)
                                                          VisualTreeHelper.GetParent(AssociatedObject);
                                                      _canvas = (Canvas) VisualTreeHelper.GetParent(_parent);
                                                  }
                                                  Point pointOnCanvas = e.GetPosition(_canvas);
                                                  var point = new Point(pointOnCanvas.X - _mouseStartPosition.X,
                                                                        pointOnCanvas.Y - _mouseStartPosition.Y);

                                                  double currentTop = Canvas.GetTop(_parent);
                                                  double currentLeft = Canvas.GetLeft(_parent);
                                                  Canvas.SetTop(_parent, currentTop + point.Y);
                                                  Canvas.SetLeft(_parent, currentLeft + point.X);

                                                  _mouseStartPosition = pointOnCanvas;
                                                  double centerY = currentTop + AssociatedObject.ActualHeight/2;
                                                  double centerX = currentLeft + AssociatedObject.ActualWidth/2;

                                                  _projectCardViewModel.CenterPoint = new Point(centerX, centerY);


                                                  var cardWallViewModel = ((ICardWallViewModel) cardWallControl.DataContext);

//                                                  double minDist = 10000;
//                                                  if (_nearestProjectCard != null)
//                                                  {
//                                                      _nearestProjectCard.ShowHighlighted = false;
//                                                  }
//                                                  _nearestProjectCard = null;
//                                                  IEnumerable<IProjectCardViewModel> projectCards =
//                                                      cardWallViewModel.ProjectCards.Where(
//                                                          c => c.IsCardVisibleInCurrentWall);
//                                                  foreach (IProjectCardViewModel projectCard in projectCards)
//                                                  {
//                                                      if (projectCard.CardNumber == _projectCardViewModel.CardNumber)
//                                                      {
//                                                          continue;
//                                                      }
//
//                                                      if (projectCard.PrimaryCard != null)
//                                                      {
//                                                          continue;
//                                                      }
//
//                                                      double x = projectCard.CenterPoint.X -
//                                                                 _projectCardViewModel.CenterPoint.X;
//                                                      double y = projectCard.CenterPoint.Y -
//                                                                 _projectCardViewModel.CenterPoint.Y;
//                                                      double currentDist = Math.Sqrt(x*x + y*y);
//                                                      if (currentDist < minDist && currentDist < 100)
//                                                      {
//                                                          minDist = currentDist;
//                                                          _nearestProjectCard = projectCard;
//                                                      }
//                                                  }
//
//                                                  if (_nearestProjectCard != null)
//                                                  {
//                                                      _nearestProjectCard.ShowHighlighted = true;
//                                                  }
//

                                                  IEnumerable<UIElement> elements =
                                                      VisualTreeHelper.FindElementsInHostCoordinates(pointOnCanvas,
                                                                                                     cardWallControl);
                                                  foreach (UIElement uiElement in elements)
                                                  {
                                                      if (uiElement.GetType() == typeof (Rectangle) &&
                                                          (
                                                              (((Rectangle) uiElement).Name == "ReadyForDev") ||
                                                              (((Rectangle) uiElement).Name == "InDev") ||
                                                              (((Rectangle) uiElement).Name == "InQA") ||
                                                              (((Rectangle) uiElement).Name ==
                                                               "ReadyForRegressionTesting") ||
                                                              (((Rectangle) uiElement).Name == "Closed"))
                                                          )
                                                      {
                                                          cardWallViewModel.SelectedStoryStatus =
                                                              (StoryStatus)
                                                              Enum.Parse(typeof (StoryStatus),
                                                                         ((Rectangle) uiElement).Name, true);
                                                      }
                                                  }
                                              }
                                          };
        }

        private void ProjectCard_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Position")
            {
                SetCardInPosition();
            }
        }

        private void SetCardInPosition()
        {
            if (_parent == null)
            {
                _parent = (ContentPresenter) VisualTreeHelper.GetParent(AssociatedObject);
                _canvas = (Canvas) VisualTreeHelper.GetParent(_parent);
            }
            Canvas.SetTop(_parent, _projectCardViewModel.Position.Y);
            Canvas.SetLeft(_parent, _projectCardViewModel.Position.X);

        }
    }
}